﻿using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace BTS.Helpers
{
    /// <summary>
    /// 日志类型枚举:Error,Warn,Info,Debug
    /// </summary>
    public enum LogLevel
    {
        Error,
        Warn,
        Info,
        Debug
    }

    public class Logger
    {
        private readonly string _filePath;//Log文件地址
        private readonly string _fileName;//Log文件名
        private readonly Thread LogThread;//执行线程
        private readonly ConcurrentQueue<string> LogQueue; //自定义线程安全的Queue
        private LogLevel _logLevel;//日志追踪等级
        private readonly object SyncRoot;//同步锁标志
        private readonly AutoResetEvent AutoReset = null;
        private Int32 _buffSize = 0;//缓存数据长度

        /// <summary>
        /// 初始化Log日志
        /// </summary>
        /// <param name="FilePath">日志地址</param>
        /// <param name="FileName">日志名称</param>
        /// <param name="logLevel">日志等级</param>
        public Logger(string FilePath, string FileName, LogLevel logLevel, int BuffSize = 1024)
        {
            AutoReset = new AutoResetEvent(false);
            SyncRoot = new object();
            LogQueue = new ConcurrentQueue<string>();

            this._filePath = FilePath;
            this._fileName = FileName + ".log";
            this._logLevel = logLevel;
            this._buffSize = BuffSize;

            LogThread = new Thread(WriteLog);
            LogThread.IsBackground = true;//后台线程，程序关闭时线程关闭；
            LogThread.Start();
        }

        /// <summary>
        /// 记录日志，受日志等级限制
        /// </summary>
        /// <param name="msg">日志内容</param>
        /// <param name="type">日志类型</param>
        private void Log(string msg, LogLevel type)
        {
            if (this._logLevel >= type)
            {
                string _msg = string.Format("{0} [{1}] {2}", DateTime.Now.ToString("HH:mm:ss.fff"), type, msg);
                LogQueue.Enqueue(_msg);
                AutoReset.Set();
            }
        }

        /// <summary>
        /// Error等级的日志
        /// </summary>
        /// <param name="msg"></param>
        public void LogError(string msg)
        {
            Log(msg, LogLevel.Error);
        }

        /// <summary>
        /// Warning等级的日志
        /// </summary>
        /// <param name="msg"></param>
        public void LogWarn(string msg)
        {
            Log(msg, LogLevel.Warn);
        }

        /// <summary>
        /// Info等级的日志
        /// </summary>
        /// <param name="msg"></param>
        public void LogInfo(string msg)
        {
            Log(msg, LogLevel.Info);
        }

        /// <summary>
        /// Debug等级的日志
        /// </summary>
        /// <param name="msg"></param>
        public void LogDebug(string msg)
        {
            Log(msg, LogLevel.Debug);
        }

        /// <summary>
        /// 记录异常日志，不受日志等级限制
        /// </summary>
        /// <param name="ex">异常</param>
        public void LogException(Exception ex)
        {
            if (ex != null)
            {
                string _newLine = Environment.NewLine;
                StringBuilder _builder = new StringBuilder();
                _builder.AppendFormat("{0}: {1}{2}", DateTime.Now.ToString("HH:mm:ss.fff"), ex.Message, _newLine);
                _builder.AppendFormat("{0}{1}", ex.GetType(), _newLine);
                _builder.AppendFormat("{0}{1}", ex.Source, _newLine);
                _builder.AppendFormat("{0}{1}", ex.TargetSite, _newLine);
                _builder.AppendFormat("{0}{1}", ex.StackTrace, _newLine);
                LogQueue.Enqueue(_builder.ToString());
                AutoReset.Set();
            }
        }

        /// <summary>
        /// 写入队列
        /// </summary>
        private void WriteLog()
        {
            StringBuilder strBuilder = new StringBuilder();

            while (true)
            {
                if (LogQueue.Count() > 0)
                {
                    string _msg;
                    LogQueue.TryDequeue(out _msg);

                    if (!CreateDirectory(_filePath + @"\" + DateTime.Now.ToString("yyyyMMdd")))
                        continue;

                    if (!string.IsNullOrWhiteSpace(_msg))
                    {
                        strBuilder.Append(_msg).AppendLine();
                    }

                    if (strBuilder.Length >= _buffSize)//日志数据长度达到1024先记录下;防止异常时过多的丢失数据
                    {
                        try
                        {
                            Monitor.Enter(SyncRoot);
                            string _path = _filePath + @"\\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + _fileName;
                            if (CreateFile(_path))
                                ProcessWriteLog(_path, strBuilder.ToString()); //写入日志到文本
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(string.Format("同步1写入日志失败，原因:{0}", ex.Message));
                        }
                        finally
                        {
                            Monitor.Exit(SyncRoot);
                        }
                        strBuilder.Clear();
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(strBuilder.ToString()))
                    {
                        try
                        {
                            Monitor.Enter(SyncRoot);
                            string _path = _filePath + @"\" + DateTime.Now.ToString("yyyyMMdd") + @"\" + _fileName;

                            if (CreateFile(_path))
                                ProcessWriteLog(_path, strBuilder.ToString()); //写入日志到文本
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(string.Format("同步2写入日志失败，原因:{0}", ex.Message));
                        }
                        finally
                        {
                            Monitor.Exit(SyncRoot);
                        }
                        strBuilder.Clear();
                    }
                    //在这里,线程会被暂停,直到收到信号;
                    AutoReset.WaitOne();
                }
            }
        }

        /// <summary>
        /// 写入文件动作
        /// </summary>
        /// <param name="path">文件路径返回文件名</param>
        /// <param name="msg">写入内容</param>
        private void ProcessWriteLog(string path, string msg)
        {
            try
            {
                StreamWriter _sw = new StreamWriter(path, true, Encoding.GetEncoding("utf-8"));
                _sw.Write(msg);
                _sw.Flush();
                _sw.Close();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("写入日志失败，原因:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 创建日志文件夹
        /// </summary>
        /// <returns></returns>
        private bool CreateDirectory(string path)
        {
            bool _result = false;
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                    if (Directory.Exists(path))
                        _result = true;
                    else
                        _result = false;
                }
                else
                    _result = true;
            }
            catch (Exception)
            {
                _result = false;
            }
            return _result;
        }

        /// <summary>
        /// 创建日志文件
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns></returns>
        private bool CreateFile(string path)
        {
            bool _result = true;
            try
            {
                if (!File.Exists(path))
                {
                    FileStream _files = File.Create(path);
                    _files.Close();
                }
            }
            catch (Exception)
            {
                _result = false;
            }
            return _result;
        }
    }
}